package lc.com.lcpicturebackend.service.impl;

import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 功能：
 * 作者：lc
 * 日期：2025/5/22 13:02
 */
@Service
@Slf4j
public class MailServiceImpl {
    @Resource
    private MailSender mailSender;

    @Resource
    private SimpleMailMessage templateMessage;

    /**
     * 发送邮件
     *
     * @param email 邮箱
     * @param code  验证码
     */
    @Async
    public void sendEmail(String email, String code) {
        try {
            SimpleMailMessage msg = new SimpleMailMessage(templateMessage);
            msg.setTo(email);
            msg.setText(String.format("您的验证码是：%s 有效期5分钟，请勿泄露给他人。", code));
            this.mailSender.send(msg);
            log.info("验证码发送成功，邮箱：{}，验证码：{}", email, code);
        } catch (MailSendException e) {
            log.error("邮件发送失败，邮箱：{}", email, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "邮件发送失败，请检查邮箱地址");
        } catch (MailException e) {
            log.error("邮件服务异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "邮件服务暂时不可用");
        }
    }
}
